# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'http://pay.pay592.com/payapi/pay?input_charset=UTF-8'

# 商户号：18888416584
# 商户密钥：ef83b6689435bbc3f4a23e474daa6513 修改密钥
# 接入终端号：1802144431
APP_CONF = {
    '18888416584': {
        'API_KEY': 'ef83b6689435bbc3f4a23e474daa6513',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


# 1.网银
# 2. weixin_scan 微信
# 3. alipay_scan  支付宝
# 4.mobile_scan  手机支付宝
# 5.mobile_wx  手机微信Wap(H5)支付
# 6.weixin  手机微信二维码
def _get_pay_type(service):
    if service == 'alipay':
        # return 'mobile_scan'
        return '4'
    elif service == 'wxpay':
        # return 'mobile_wx'
        return '5'
    else:
        # return 'mobile_wx'
        return '5'


def generate_sign(parameter, key):
    '''  生成下单签名 '''
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k] != '' and parameter[k] != None:
            if k != 'notify_url':
                s += '%s=%s&' % (k, parameter[k])
    s += key
    _LOGGER.info("hbtpay sign str : %s", s)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def verify_notify_sign(params, key):
    sign = params['signMsg']
    params.pop('signMsg')
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("hbtpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _build_form(params):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + _GATEWAY + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    parameter_dict = OrderedDict((
        ('user_no', app_id),
        ('bill_no', str(pay.id)),
        ('bill_time', time.strftime("%Y%m%d", time.localtime())),
        ('money', '%.2f' % pay_amount),
        ('product_desc', 'charge'),
        ('client_ip', _get_device_ip(info)),
        ('return_url', '{}/pay/api/{}/hbtpay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, app_id)),
        ('notify_url', '{}/pay/api/{}/hbtpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('bank_code', ''),
        ('choosePayType', _get_pay_type(service)),
    ))
    parameter_dict['signMsg'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("hbtpay create  data: %s, url: %s", parameter_dict, _GATEWAY)
    html_text = _build_form(parameter_dict)
    cache_id = redis_cache.save_html(pay.id, html_text)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# success
def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("hbtpay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['bill_no']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('hbtpay event does not contain pay ID')

    pay = order_db.get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['orderStatus'])
    trade_no = data['orderNo']
    total_fee = float(data['money'])

    extend = {
        'trade_status': 'success',
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    # 0未支付，1成功，2失败
    if trade_status == '1':
        _LOGGER.info('hbtpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pass
